package com.mall.order.mq.delay;

import com.alibaba.druid.sql.visitor.functions.Now;
import com.google.errorprone.annotations.Var;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.StockMapper;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
import static org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus.RECONSUME_LATER;

/**
 * @Description: ${DESCRIPTION}
 * @Author: 徐能雄
 * @Date: 2021/10/4 22:31
 */
@Component
public class DelayOrderCancelConsumer {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    StockMapper stockMapper;

    DefaultMQPushConsumer consumer;

    @PostConstruct
    public void init() {

        //1. 创建Consumer对象
        consumer = new DefaultMQPushConsumer("delay_cancel_order_consumer");

        //2. 设置nameerver地址
        consumer.setNamesrvAddr("127.0.0.1:9876");

        //3. 设置MessageListener
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {

                //当消费到该消息时，意味着订单的延时时间已达到
                //从消息中获取orderId，去数据库中查询订单状态
                MessageExt message = msgs.get(0);
                //String orderId = message.getBody().toString();
                byte[] body = message.getBody();
                String orderId = new String(body,0,body.length, Charset.forName("utf-8"));

                Order order = orderMapper.selectByPrimaryKey(orderId);
                Integer status = order.getStatus();

                //如果订单仍为初始化状态，意味着订单没有支付，执行订单取消操作
                if (0 == status){
                    //修改订单状态为已取消
                    order.setStatus(7);
                    order.setUpdateTime(new Date());
                    orderMapper.updateByPrimaryKey(order);

                    //还原商品的库存（遍历订单商品条目，根据订单购买数量修改stock_count,lock_conunt）
                    List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
                    for ( OrderItem orderItem : orderItems){
                        Stock stock = stockMapper.selectStock(orderItem.getItemId());

                        stock.setStockCount(stock.getStockCount()+orderItem.getNum());
                        stock.setLockCount(stock.getLockCount()-orderItem.getNum());

                        stockMapper.updateByPrimaryKey(stock);
                    }
                }

                //如果订单已经支付，则不做任何处理
                return CONSUME_SUCCESS;
            }
        });


        try {
            //4. 订阅主题
            consumer.subscribe("delay_order_cancel", "*");
            //5. 启动消费者
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }


    }
}